import { Service } from 'egg';
import { Admin } from '../model/Admin';
import * as md5 from 'blueimp-md5';

export default class AdminService extends Service {
    /**
     * 处理后台登录事件
     * @param {string} admin_username
     * @param {string} admin_password
     * @returns {Promise<any>}
     */
    public async login(admin_username: string, admin_password: string) {
        try {
            admin_password = md5(admin_password + 'linglan');
            const admin: any = await this.ctx.model.Admin.findOne<Admin>({
                attributes: ['admin_id', 'admin_username', 'admin_password'],
                where: {
                    admin_username,
                    admin_password
                },
            });
            if (!admin) {
                throw new Error(JSON.stringify({ code: 2, msg: '登录失败（用户名或密码错误）' }));
            }
            return admin;
        } catch (e) {
            this.ctx.logger.error(e);
            throw new Error(e.message);
        }
    }

    /**
     * 更新token
     * @param {string} admin_username
     * @param {string} admin_token
     * @param {string} updated_time
     * @returns {Promise<any>}
     */
    public async updateToken(admin_id: string, admin_token: string) {
        const result = await this.ctx.model.Admin.update({ admin_token }, {
            where:
            {
                admin_id,
            },
        },
        );
        if (!result) {
            throw new Error(JSON.stringify({ code: 2, msg: '更新token失败' }));
        }
        return result;
    }

    /**
     *
     * @param token 根据token查找用户
     */
    public async searchAdminByToken(token: string) {
        try{
            const admin = await this.ctx.model.Admin.findOne<Admin>({
                attributes: ['admin_id', 'admin_username', 'admin_password'],
                where: {
                    admin_token: token,
                },
            });
            if (!admin) {
                throw new Error(JSON.stringify({ code: -1, msg: '您还未登录，请登录' }));
            }
            return admin;
        }catch(e){
            this.ctx.logger.error(e);
            throw new Error(e.message);
        }
    }

    /**
     *
     * @param token 根据token查找用户
     */
    public async searchAdminIdByToken(token: string) {
        try{
            const admin = await this.ctx.model.Admin.findOne<Admin>({
                attributes: ['admin_id', 'admin_username', 'admin_password'],
                where: {
                    admin_token: token,
                },
            });
            if (!admin) {
                return { admin_id: '' };
            }
            return admin;
        }catch(e){
            this.ctx.logger.error(e);
            throw new Error(e.message);
        }
    }

}
